/*
 * Created on Sun Oct 01 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import type { ILoginStrategy } from './ILoginStrategy';
import type { LoginParam } from '../types';
import type { UserInfo } from '../types';
import { createError } from '../../../utils/ErrorUtils';
import User from '../../../db/models/User';
import { ErrorCode } from '../../../constants';
import{ isPhone } from '../../../utils/CheckUtils';

export default class AccountEncryptPwdStrategy implements ILoginStrategy {
  async login(param: LoginParam): Promise<UserInfo> {
    if (!param.account) {
      throw createError(401, '缺少账户名', ErrorCode.REQUIRE_ACCOUNT);
    }

    if (!param.encryptPwd) {
      throw createError(401, '缺少密码', ErrorCode.REQUIRE_PWD);          
    }

    let user = undefined;
    if (isPhone(param.account)) {
      //手机密码登录 匹配手机号
      user = await User.findOne({ phone: param.account }).exec();      
    } else {
      //其他情况匹配用户名
      user = await User.findOne({ userName: param.account }).exec();            
    }


    if (user) {
      if (user.encryptPwd !== param.encryptPwd) {
        throw createError(401, '密码错误', ErrorCode.PWD_ERROR);        
      }
      
      return user.toUserInfo();
    } else {
      throw createError(401, '用户不存在', ErrorCode.USER_NOT_EXIST);
    }
  }
}